import {
    login,
    regist,
    verifyUserByEmail,
    verifyUserByUsername,
    getVerifyCode,
    sendMailForget
} from "../api/user";

import {
    setOrderStatus
} from "../api/admin";

const baseMixin = {
    data() {
        //验证注册用户名是否可用
        const validateRegistUsername = (rule, value, callback) => {
            if (typeof value === 'undefined') {
                callback(new Error("请输入用户名!"));
            } else {
                verifyUserByUsername(value).then((res) => {
                    if (res.data) {
                        callback(new Error(res.message));
                    } else {
                        callback();
                    }
                }).catch((err) => {
                    this.$message.error(err)
                })
            }
        };
        // 验证邮箱格式与是否已经注册
        const validateEmail = (rule, value, callback) => {
            if (typeof value === 'undefined') {
                callback(new Error("请输入邮箱!"));
            } else {
                // 如果输入了内容 但是格式不对 也不放
                let regExp = /^([a-zA-Z0-9]+[-_\.]?)+@[a-zA-Z0-9]+\.[a-z]+$/;
                let emailIsValid = regExp.test(value)
                if (!emailIsValid) {
                    callback(new Error('您的邮箱输入有误，请重新输入！'));
                } else {
                    //格式正确 判断是否已被注册
                    verifyUserByEmail(value).then((res) => {
                        let flag = res.data
                        if (flag) {
                            callback(new Error('抱歉，该邮箱已被注册！'));
                        } else {
                            callback();
                            this.disabled = false;
                            this.verifyBtnType = 'success';
                        }
                    }).catch((err) => {
                        this.$message.error(err)
                    })
                }

            }
        };
        // 验证二次密码
        const validateSec = (rule, value, callback) => {
            if (typeof value === 'undefined') {
                callback(new Error("请再次输入密码!"));
            } else if (value !== this.registForm.firstpassword) {
                callback(new Error("两次输入密码不一致!"));
            } else {
                callback();
            }
        };
        return {
            customerInfoForm: {},
            loginForm: {},
            loginFormRules: {
                username: [{
                    required: true,
                    message: "用户名不可为空！",
                    trigger: "blur"
                },],
                password: [{
                    required: true,
                    message: "请先输入密码！",
                    trigger: "blur"
                },],
            },
            formLabelWidth: "100px",
            dialogLoginFormVisible: false,
            dialogRegistFormVisible: false,
            dialogForgetPwdVisible: false,
            registForm: {},
            registFormRules: {
                username: [{
                    required: true,
                    // message: "用户名不可为空！",
                    validator: validateRegistUsername,
                    trigger: "blur"
                },],
                firstpassword: [{
                    required: true,
                    message: "密码不可为空！",
                    trigger: "blur"
                },],
                secondpassword: [{
                    required: true,
                    validator: validateSec,
                    trigger: "blur",
                },],
                email: [{
                    required: true,
                    validator: validateEmail,
                    trigger: "blur",
                },],
            },
            tableData: [{
                date: '2016-05-02',
                name: '王小虎',
                address: '上海市普陀区金沙江路 1518 弄',
            }, {
                date: '2016-05-04',
                name: '王小虎',
                address: '上海市普陀区金沙江路 1518 弄'
            }, {
                date: '2016-05-01',
                name: '王小虎',
                address: '上海市普陀区金沙江路 1518 弄',
            }, {
                date: '2016-05-03',
                name: '王小虎',
                address: '上海市普陀区金沙江路 1518 弄'
            }],
            isLoginStatus: false,
            sendCodeCountDown: 60,
            disabled: false,
            verifyBtnState: '获取验证码',
            verifyBtnType: 'info',
            emailForget: '',
        }
    },
    computed: {
        getUserInfoFromSS() {
            return sessionStorage.getItem("userInfo");
        }
    },
    methods: {
        //根据id获得供应商信息
        async selectSupplierById(id) {
            let supplier = {};
            await selectSupplierById(id).then((res) => {
                supplier = res.data;
            })
            return supplier;
        },
        //获得用户信息
        getUserInfo() {
            let objUserInfo = sessionStorage.getItem("userInfo");
            if (objUserInfo !== null) {
                let strUserInfo = JSON.parse(objUserInfo);
                let user = strUserInfo.data;
                return user;
            } else {
                return null;
            }
        },
        // 登录
        loginSubmit(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    login(this.loginForm).then((res) => {
                        let apiResponse = res.apiResponse;
                        let token = res.token;
                        let code = apiResponse.code;
                        let message = apiResponse.message;
                        if (code === 404 || code === 201) {
                            this.$message.error(message);
                        } else {
                            sessionStorage.setItem("userInfo", JSON.stringify(apiResponse));
                            sessionStorage.setItem("role", apiResponse.data.role);
                            sessionStorage.setItem("token", token);
                            location.reload();
                        }
                    })
                } else {
                    return false;
                }
            });
        },
        // 注册
        registSubmit(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    regist(this.registForm).then((res) => {
                        let code = res.code;
                        let message = res.message;
                        if (code === 10011 || code === 201) {
                            this.$message.error(message);
                        } else {
                            this.$message.success(message);
                            location.reload();
                        }

                    }).catch((err) => {
                        this.$message.error(err)
                    })

                } else {
                    return false;
                }
            });
        },
        // 注销
        logOut() {
            if (sessionStorage.getItem("userInfo") === null) {
                return;
            }
            sessionStorage.removeItem("userInfo");
            if (this.$route.path === "/") {
                location.reload()
            }
            this.$router.push('/');
        },
        // 切换注册对话框
        toRegist() {
            this.dialogLoginFormVisible = false;
            this.dialogRegistFormVisible = true;
        },
        // 切换忘记密码对话框
        toForgetPassword() {
            this.dialogLoginFormVisible = false;
            this.dialogForgetPwdVisible = true;
        },
        // 返回登录对话框
        goBack() {
            this.dialogLoginFormVisible = true;
            this.dialogRegistFormVisible = false;
        },
        // 设置登陆对话框显示状态
        setDialogFormVisible(newDialogFormVisible) {
            this.dialogLoginFormVisible = newDialogFormVisible;
        },
        // 发送重置密码给邮箱
        sendForgetEmail() {
            let email = this.emailForget;

            //首先检查邮箱格式
            let regExp = /^([a-zA-Z0-9]+[-_\.]?)+@[a-zA-Z0-9]+\.[a-z]+$/;
            let emailIsValid = regExp.test(email)
            if (!emailIsValid) {
                this.$message.error('您输入的邮箱不符合格式！');
                return;
            }

            sendMailForget(email).then((res) => {
                let code = res.code;
                let message = res.message;
                if (code === 201) {
                    this.$message.error(message);
                } else {
                    this.$message.success(message);
                }
            }).catch((err) => {
                this.$message.error(err)
            });
        },
        // 检查用于在session中的登录状态
        checkUserLoginStatus() {
            return sessionStorage.getItem("userInfo") !== null;
        },
        // 检查订单信息的状态 登录才能显示
        changeOrderVisible(flag) {
            let loginStatus = this.checkUserLoginStatus();
            if (loginStatus) {
                this.orderVisible = flag;
            } else {
                this.$message.error("请您去首页登录！");
            }
        },
        //获得图片静态资源
        getCharIconSrc(producttype, productname) {
            if (typeof productname === 'undefined') {
                return;
            }
            return require("../assets/image/" + producttype + "/" + productname + ".jpg");
        },
        //规定时间内获取邮箱验证码
        verifyEmail() {
            if (typeof this.registForm.email === 'undefined') {
                this.$message.error('您好，请输入邮箱！');
                return;
            } else {
                this.verifyBtnState = '正在发送...';
                this.disabled = true;
                //高效定时器
                let _this = this;
                let i = setInterval(() => {
                    _this.sendCodeCountDown--;
                    if (_this.sendCodeCountDown === 0) {
                        _this.verifyBtnState = '获取验证码';
                        _this.disabled = false;
                        clearInterval(i);
                    }
                }, 1000);
                this.sendCodeCountDown = 60;
                //获取验证码
                getVerifyCode(this.registForm.email, this.registForm.username).then((res) => {
                    this.$message.success(res.data.message)
                }).catch((err) => {
                    this.$message.error(err)
                })

            }
        },
        // 管理员修改订单状态
        setOrderStatus(orderid, code) {
            setOrderStatus(this.role, orderid, code)
                .then((res) => {
                    let code = res.code;
                    let message = res.message;
                    if (code === 201) {
                        this.$message.error(message);
                    } else {
                        this.$message.success(message);
                        this.selectAllCustomerOrders();
                    }
                })
                .catch((err) => {
                    this.$message.error(err);
                });
        },
    },
}

export default baseMixin